<template>
  <div>
    <el-form ref="myform" :model="formItem" label-width="100px" size="mini">
      <el-row :gutter="40">
        <el-col :span="12">
          <el-form-item label="规则名称" prop="name">
            <el-input v-model="formItem.name" disabled />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="班次" prop="classesId">
            <el-input v-model="formItem.classesName" disabled />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="小组数" prop="groupNumber">
            <el-input v-model="formItem.groupNumber" disabled />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="包含节假日" prop="isIncludedHoliday">
            <el-select v-model="formItem.isIncludedHoliday" filterable remote disabled>
              <el-option v-for="(item) in isIncludedHolidayList" :key="item.code" :label="item.name" :value="item.code" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <div class="form-info-title">
      <i class="el-icon-document" /><span>小组</span>
    </div>
    <div class="rule-group">
      <draggable :list="groupList" :group="{ name: 'group', pull: 'clone', put: false }" :set-data="setData">
        <div v-for="element in groupList" :key="element.code" class="rule-group-item">
          {{ element.name }}
        </div>
      </draggable>
    </div>
    <div class="form-info-title">
      <i class="el-icon-document" /><span>周期管理</span>
      <div>
        <el-button size="mini" icon="el-icon-plus" @click="ruleAdd">添加</el-button>
        <el-button v-if="formItem.cyclical.length > 0" size="mini" icon="el-icon-delete" @click="remove">删除一个周期</el-button>
      </div>
    </div>
    <div class="rule-group-body">
      <div v-for="(cycle,ind) in formItem.cyclical" :key="ind">
        <el-card class="box-card" body-style="padding:5px; height:240px; overflow:auto;">
          <div slot="header" class="clearfix">
            <span>周期{{ ind + 1 }}</span>
            <!-- <el-button type="text" title="删除" size="mini" icon="el-icon-delete" style="float: right; padding: 3px 0" @click="remove(ind)" /> -->
          </div>
          <div v-for="(item,index) in cycle.classesItems" :key="index" class="board-column">
            <div class="board-column-header">{{ '[' +item.name +'   ' + item.startTime +'至' + item.endTime +']' }} </div>
            <draggable :list="item.rules" class="board-column-content" group="group" @add="evt => ruleItemAdd(ind,index)">
              <div v-for="(element,dex) in item.rules" :key="dex" class="board-item">
                {{ element.name }} <span class="icon-margin"><i class="el-icon-delete" @click="removeRuleItem(ind,index,dex)" /></span>
              </div>
            </draggable>
          </div>
        </el-card>
      </div>
    </div>
  </div>
</template>

<script>
import draggable from 'vuedraggable'
import {
  update,
  detail
} from '@neu/dcom-ui/api/schedulingrule'
import { list } from '@neu/dcom-ui/api/classes'

// 定义一个表单原始项
const formItem = {
  name: '',
  classesId: null,
  groupNumber: null,
  isIncludedHoliday: false,
  classes: {
    items: []
  },
  cyclical: [],
  cycleNumber: 0
}
export default {
  name: 'SchedulingruleEditForm',
  components: {
    draggable
  },
  props: {
    // 根据id可判断是新建还是更新
    id: {
      required: false,
      type: Number,
      default: -1
    }
  },
  data() {
    return {
      group: 'kanbanGroup',
      // 编辑的表单内容
      formItem: {
        ...formItem
      },
      // 是否包含节假日列表
      isIncludedHolidayList: [
        { name: '是', code: true },
        { name: '否', code: false }
      ],
      // 小组下拉
      groupList: [],
      list: [],
      // 班次列表
      classesList: [],
      // 班次周期数
      classesNum: 0
    }
  },
  watch: {
    // 监控id的变化，初始化表单数据
    id: function() {
      this.fetch()
    }
  },
  created() {
    list({}).then(res => { this.classesList = res.data })
    this.fetch()
  },
  methods: {
    setData(dataTransfer) {
      // to avoid Firefox bug
      // Detail see : https://github.com/RubaXa/Sortable/issues/1012
      dataTransfer.setData('Text', '')
    },
    // 初始化表单数据
    fetch() {
      if (this.id !== -1) {
        detail(this.id).then(response => {
          const data = response.data
          // 生成小组下拉列表
          for (var i = 1; i <= data.groupNumber; i++) {
            this.groupList.push({ code: i, name: '第' + i + '组' })
          }
          // 班次周期数
          data.classes.items.forEach(k => {
            if (this.classesNum < k.cycle) {
              this.classesNum = k.cycle
            }
          })

          // 生成前台数据结构
          const items = data.items
          const setItems = new Set(data.classes.items.map(e => e.cycle))

          let j = 0
          for (let i = 1; i <= data.cycleNumber; i++) {
            console.log(data.cycleNumber)
            setItems.forEach(m => {
              j++
              const item = { classesItems: [] }

              data.classes.items.filter(k => k.cycle === m).forEach(s => {
                const rules = items.filter(n => n.cyclicalNumber === j && s.code === n.classesItemCode).map(s => {
                  return { code: s.groupNumber, name: s.groupName }
                })
                item.classesItems.push({ ...s, rules: rules })
              })
              if (!data.cyclical) { data['cyclical'] = [] }
              data.cyclical.push(item)
            })
          }

          if (!data.cyclical) {
            data['cyclical'] = []
          }
          // 移除items 属性
          delete data.items
          this.formItem = {
            ...data
          }
        })
      } else {
        this.formItem = {
          ...formItem
        }
      }
    },
    // 保存操作，返回promise，后续处理交由调用者处理
    save() {
      const saveObj = { ...this.formItem, items: [] }
      this.formItem.cyclical.forEach((a, index) => {
        a.classesItems.forEach((b, ind) => {
          b.rules.forEach((c, dex) => {
            const rule = {
              // 周期顺序
              cyclicalNumber: index + 1,
              classesItemName: b.name,
              classesItemCode: b.code,
              startTime: b.startTime,
              endTime: b.endTime,
              groupNumber: c.code,
              groupName: c.name
            }
            saveObj.items.push(rule)
          })
        })
      })

      return new Promise(resolve => {
        if (saveObj.items.length < 1) {
          this.$message({
            showClose: true,
            message: '至少排一班次',
            type: 'error'
          })
          return resolve(false)
        } else {
          resolve(update(this.id, saveObj))
        }
      })
    },
    reset() {
      this.$refs.myform.resetFields()
    },
    // 添加周期
    ruleAdd() {
      const self = this
      const setItems = new Set(self.formItem.classes.items.map(e => e.cycle))
      setItems.forEach(m => {
        const item = { classesItems: [] }
        self.formItem.classes.items.filter(k => k.cycle === m).forEach(s => {
          item.classesItems.push({ ...s, rules: [] })
        })

        if (!self.formItem.cyclical) { self.formItem['cyclical'] = [] }
        self.formItem.cyclical.push(item)
      })

      this.formItem.cycleNumber = this.formItem.cycleNumber + 1
    },
    // 移除一个周期
    remove() {
      for (let i = 0; i < this.classesNum; i++) {
        this.formItem.cyclical.pop()
      }
      this.formItem.cycleNumber = this.formItem.cycleNumber - 1
    },
    // 过滤重复性元素
    ruleItemAdd(ind, index) {
      const ruleItems = this.formItem.cyclical[ind].classesItems[index].rules
      const filterCode = Array.from(new Set(ruleItems.map(e => e.code)))
      const filterData = []
      if (filterCode.length !== ruleItems.length) {
        ruleItems.forEach(e => {
          const index = filterCode.indexOf(e.code)
          if (index > -1) {
            filterData.push(e)
            filterCode.splice(index, 1)
          }
        })
        this.formItem.cyclical[ind].classesItems[index].rules = filterData
      }
    },
    // 移除一项
    removeRuleItem(ind, index, dex) {
      this.formItem.cyclical[ind].classesItems[index].rules.splice(dex, 1)
    }
  }
}
</script>

<style lang="scss" scoped>
.board-column {
  // min-width: 300px;
  // min-height: 414px;
  height: auto;
  overflow: hidden;
  border: 1px solid #ebeef5;
  border-radius: 4px;

  .board-column-header {
    height: 40px;
    line-height: 40px;
    overflow: hidden;
    padding: 0 20px;
    text-align: center;
    color: #606266;
    border-radius: 4px 4px 0 0;
    font-size: 14px;
  }

  .board-column-content {
    height: auto;
    overflow: hidden;
    border: 5px solid transparent;
    min-height: 60px;
    display: flex;
    justify-content: flex-start;
    flex-direction: column;
    align-items: center;
    font-size: 14px;

    .board-item {
      cursor: pointer;
      width: 100%;
      height: 33px;
      margin: 3px 0;
      background-color: #F0F0F0;
      text-align: left;
      line-height: 33px;
      padding: 0px 10px;
      box-sizing: border-box;
      box-shadow: 0px 1px 3px 0 rgba(0, 0, 0, 0.2);
      color: #777;
    }
  }
  .icon-margin{
    margin-left: 70%;
  }
}
.rule-group{
  border: 1px solid #ebeef5;
  border-radius: 4px;
  padding: 3px;
  & > div{
    display: flex;
  }
}
.rule-group-item{
    cursor: pointer;
    width: 100%;
    height: 33px;
    margin: 3px;
    background-color: #F0F0F0;
    text-align: left;
    line-height: 33px;
    padding: 0px 10px;
    box-sizing: border-box;
    box-shadow: 0px 1px 3px 0 rgba(0, 0, 0, 0.2);
    color: #777;
}
.rule-group-body{
  height:calc(100vh - 495px);
  overflow: auto;
  & > div{
    display: inline-block;
    vertical-align: top;
    width:33.33%;
    padding-right: 15px;
    padding-bottom: 15px;
    box-sizing: border-box;
  }
  & > div:nth-child(3n){ padding-right: 0;}
  & > div:nth-last-child(3){ padding-bottom: 0;}
  & > div:nth-last-child(2){ padding-bottom: 0;}
  & > div:nth-last-child(1){ padding-bottom: 0;}
}
</style>
